package com.hmall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmall.common.client.ItemClient;
import com.hmall.common.dto.Item;
import com.hmall.common.dto.PageDTO;
import com.hmall.search.pojo.ItemDoc;
import com.hmall.search.pojo.RequestParams;
import com.hmall.search.service.SearchService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.elasticsearch.search.suggest.completion.CompletionSuggestionBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SearchServiceImpl implements SearchService {
    @Autowired
    RestHighLevelClient client;
    @Autowired
    ItemClient itemClient;

    @Override
    public PageDTO<ItemDoc> search(RequestParams requestParams) {
        SearchResponse response = null;
        try {
            SearchRequest request = new SearchRequest("item");
            buildBasicQuery(requestParams, request);
            request.source().highlighter(new HighlightBuilder().field("name").requireFieldMatch(false));
            // 3.发送请求
            response = client.search(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // 4.解析响应
        return handleResponse(response);
    }

    @Override
    public Map<String, List<String>> filters(RequestParams params) {
        SearchRequest request = new SearchRequest("item");
        buildBasicQuery(params, request);
        buildFilterQuery(request);
        SearchResponse search = null;
        try {
            search = client.search(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        Aggregations aggregations = search.getAggregations();

        List<String> brandList = getTagName(aggregations, "brand_agg");
        List<String> starNameList = getTagName(aggregations, "category_agg");

        Map<String, List<String>> result = new HashMap<>();
        result.put("category", starNameList);
        result.put("brand", brandList);
        return result;
    }

    @Override
    public List<String> suggestion(String key) {
        log.info("关键词是： {}", key);
        List<String> list = new ArrayList<>();
        try {
            SearchRequest searchRequest = new SearchRequest("item");
            //自动补全查询
            searchRequest.source().suggest(new SuggestBuilder()
                    .addSuggestion("mysuggestion", new CompletionSuggestionBuilder("suggestion")
                            .prefix(key)//查询的字段
                            .skipDuplicates(true)//是否去重
                            .size(10)//补全的词条数
                    ));
            SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
            //处理结果
            CompletionSuggestion completionSuggestion = search.getSuggest().getSuggestion("mysuggestion");
            List<CompletionSuggestion.Entry.Option> options = completionSuggestion.getOptions();
//            for (CompletionSuggestion.Entry.Option option : options) {
//                String text = option.getText().toString();
//                list.add(text);
//            }
            List<String> collect = options.stream().map(option -> {
                return option.getText().toString();
            }).collect(Collectors.toList());

        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }

    @Override
    public void upOrDown(Item item) {
        if (item.getStatus() == 1) {
            // 2.转换为文档类型
            ItemDoc hotelDoc = new ItemDoc(item);
            // 3.将HotelDoc转json
            String json = JSON.toJSONString(hotelDoc);
            // 1.准备Request对象
            IndexRequest request = new IndexRequest("item").id(hotelDoc.getId().toString());
            // 2.准备Json文档
            request.source(json, XContentType.JSON);
            // 3.发送请求
            try {
                client.index(request, RequestOptions.DEFAULT);
                log.info("上架成功");
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        } else {
            DeleteRequest request = new DeleteRequest("item", item.getId().toString());
            // 2.发送请求
            try {
                client.delete(request, RequestOptions.DEFAULT);
                log.info("删除成功");
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    @Override
    public void put() {
        long start = System.currentTimeMillis();
        int pageSize = 50;
        int totalCount = itemClient.count();
        int batch = totalCount % pageSize == 0 ? totalCount / pageSize : totalCount / pageSize + 1;//次数
        CountDownLatch countDownLatch = new CountDownLatch(batch);

        ExecutorService executorService = Executors.newFixedThreadPool(10);

        for (int i = 1; i <= batch; i++) {
            IPage<Item> ItemPage = new Page<>(i, pageSize);
            PageDTO<com.hmall.common.dto.Item> itemPageDTO = itemClient.queryItemByPage(i, pageSize);
            List<Item> list = itemPageDTO.getList();
            BulkRequest request = new BulkRequest();
            executorService.submit(() -> {
                for (Item item : list) {
                    // 2.转换为文档类型
                    ItemDoc ItemDoc = new ItemDoc(item);
                    // 2.2.创建新增文档的Request对象
                    request.add(new IndexRequest("item")
                            .id(item.getId().toString())
                            .source(JSON.toJSONString(ItemDoc), XContentType.JSON));
                }
                // 2.1.转换为文档类型ItemDoc
                try {
                    client.bulk(request, RequestOptions.DEFAULT);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                countDownLatch.countDown();
            });
        }
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        executorService.shutdown();
        // 1.根据id查询酒店数据
        long end = System.currentTimeMillis();
        long res = end - start;
        System.out.println("res = " + res);
        System.out.println("耗费  " + res / 1000 + "  秒");
    }

    private List<String> getTagName(Aggregations aggregations, String aggName) {
        List<String> arrayList = new ArrayList<>();
        Terms terms = aggregations.get(aggName);
        List<? extends Terms.Bucket> buckets = terms.getBuckets();
//        for (Terms.Bucket bucket : buckets) {
//            String keyAsString = bucket.getKeyAsString();
//            arrayList.add(keyAsString);
//        }
        List<String> collect = buckets.stream().map(MultiBucketsAggregation.Bucket::getKeyAsString).collect(Collectors.toList());
        return collect;
    }

    private void buildFilterQuery(SearchRequest request) {
        request.source().size(0);
        request.source().aggregation(
                AggregationBuilders
                        .terms("brand_agg")
                        .field("brand")
                        .size(20)
        );
        request.source().aggregation(
                AggregationBuilders
                        .terms("category_agg")
                        .field("category")
                        .size(20)
        );
    }

    private void buildBasicQuery(RequestParams params, SearchRequest request) {
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        String key = params.getKey();
        if (key == null || "".equals(key)) {
            boolQuery.must(QueryBuilders.matchAllQuery());
        } else {
            boolQuery.must(QueryBuilders.matchQuery("all", key));
        }

        String brand = params.getBrand();
        String category = params.getCategory();
        Integer minPrice = params.getMinPrice();
        Integer maxPrice = params.getMaxPrice();

        Integer page = params.getPage();
        Integer size = params.getSize();
        request.source().from((page - 1) * size).size(size);

        if (category != null && !"".equals(category)) {
            boolQuery.filter(QueryBuilders.termQuery("category", category));
        }
        if (brand != null && !"".equals(brand)) {
            boolQuery.filter(QueryBuilders.termQuery("brand", brand));
        }

        if (minPrice != null && maxPrice != null) {
            boolQuery.filter(QueryBuilders.rangeQuery("price")
                    .lte(maxPrice)
                    .gte(minPrice));
        }


        String sortBy = params.getSortBy();
        if ("sold".equals(sortBy)) {
            request.source().sort("score", SortOrder.DESC);
        } else if ("price".equals(sortBy)) {
            request.source().sort("price", SortOrder.ASC);
        }
        FunctionScoreQueryBuilder functionScoreQuery =
                QueryBuilders.functionScoreQuery(
                        // 原始查询，相关性算分的查询
                        boolQuery,
                        // function score的数组
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                                // 其中的一个function score 元素
                                new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                        // 过滤条件
                                        QueryBuilders.termQuery("isAD", true),
                                        // 算分函数
                                        ScoreFunctionBuilders.weightFactorFunction(10)
                                )
                        });
        request.source().query(functionScoreQuery);

        request.source().query(boolQuery);
    }

    private PageDTO<ItemDoc> handleResponse(SearchResponse response) {

        // 4.解析响应
        SearchHits searchHits = response.getHits();
        // 4.1.获取总条数
        long total = searchHits.getTotalHits().value;
        // 4.2.文档数组
        SearchHit[] hits = searchHits.getHits();
        // 4.3.遍历
        List<ItemDoc> hotels = new ArrayList<>();
        for (SearchHit hit : hits) {
            // 获取文档source
            String json = hit.getSourceAsString();
            // 反序列化
            ItemDoc hotelDoc = JSON.parseObject(json, ItemDoc.class);

            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField highlightField = highlightFields.get("name");
            String string = "";
            if (highlightField != null) {
                Text[] fragments = highlightField.fragments();
                string = fragments[0].string();
                hotelDoc.setName(string);
            }

            // 放入集合
            hotels.add(hotelDoc);
        }
        // 4.4.封装返回
        PageDTO<ItemDoc> pageDTO = new PageDTO(total, hotels);

//        pageDTO.getList().forEach(System.out::println);
        return pageDTO;
    }
}
